package com.tools.modules.table.service.impl;

import com.tools.common.utils.DateUtils;
import com.tools.generator.ConstantGen;
import com.tools.generator.config.ToolDataSource;
import com.tools.generator.entity.TableEntity;
import com.tools.generator.entity.TableFieldEntity;
import com.tools.generator.service.DataSourceService;
import com.tools.generator.service.TableService;
import com.tools.generator.utils.QueryUtils;
import com.tools.modules.table.help.TemplateUtil;
import com.tools.modules.table.service.GenFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 生成 html 文件
 * @Author : ShangJY
 * @create 2024/6/2 13:49
 */
@Service("html")
public class HtmlFileServiceImpl implements GenFileService {

    @Autowired
    private TableService tableService;

    @Autowired
    private DataSourceService dataSource;

    @Override
    public File genFile(List<Long> tableIds) throws IOException {
        // 设置模板信息
        ClassLoaderTemplateResolver templateResolver = TemplateUtil.setTemplate();

        // 创建模板引擎
        TemplateEngine templateEngine = new TemplateEngine();
        templateEngine.setTemplateResolver(templateResolver);

        List<TableEntity> tableEntity = tableService.selectTableByIds(tableIds);
        List<TableFieldEntity> fieldList = new ArrayList<>();
        tableEntity.forEach(table->{
            ToolDataSource toolDataSource = dataSource.get(table.getDatasourceId());
            // 获取原生字段数据
            List<TableFieldEntity> tableFieldList = QueryUtils.getTableFieldList(toolDataSource, table.getId(), table.getTableName());
            fieldList.addAll(tableFieldList);
        });

        // 填充数据
        Context context = new Context();
        context.setVariable("tables", tableEntity);
        context.setVariable("data", fieldList);

        String name = DateUtils.getDateStr(DateUtils.DATE_YMDHS);
        File file = new File(ConstantGen.TEMP_DIR + ConstantGen.SEPARATOR+name+".html" );

        // 渲染模板并保存为文件
        FileWriter writer = new FileWriter(file);
        templateEngine.process("thymeleaf", context, writer);
        System.out.println("HTML 文件已生成：--->"+file.getPath());
        return file;
    }
}
